package com.cyzy.service.impl;

import com.cyzy.entity.Class;
import com.cyzy.exception.BusinessException;
import com.cyzy.mapper.ClassMapper;
import com.cyzy.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Override
    public Map<String, Object> getClassList(String keyword, String grade, int pageNum, int pageSize) {
        // 计算分页起始位置
        int start = (pageNum - 1) * pageSize;

        // 查询班级列表和总记录数
        List<Class> classList = classMapper.selectClassList(keyword, grade, start, pageSize);
        int total = classMapper.selectClassCount(keyword, grade);

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", classList);
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);

        return result;
    }

    @Override
    public Class getClassById(String id) {
        if (id == null || id.trim().isEmpty()) {
            throw new BusinessException("班级ID不能为空");
        }
        return classMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateClass(Class classEntity) {
        // 参数校验
        if (classEntity == null || classEntity.getId() == null || classEntity.getId().trim().isEmpty()) {
            throw new BusinessException("班级ID不能为空");
        }

        // 验证班级是否存在
        Class existingClass = classMapper.selectById(classEntity.getId());
        if (existingClass == null) {
            throw new BusinessException("班级不存在");
        }

        // 验证班级是否已被删除
        if (existingClass.getStatus() == 0) {
            throw new BusinessException("该班级已被删除，无法更新");
        }

        // 执行更新操作
        int rows = classMapper.update(classEntity);
        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteClass(String id) {
        // 参数校验
        if (id == null || id.trim().isEmpty()) {
            throw new BusinessException("班级ID不能为空");
        }

        // 验证班级是否存在
        Class existingClass = classMapper.selectById(id);
        if (existingClass == null) {
            throw new BusinessException("班级不存在");
        }

        // 验证班级是否已被删除
        if (existingClass.getStatus() == 0) {
            throw new BusinessException("该班级已被删除");
        }

        // 执行删除操作（逻辑删除）
        int rows = classMapper.delete(id);
        return rows > 0;
    }
}
